package huanzhao.erp.other.message;

import cn.hutool.json.JSONUtil;
import com.github.benmanes.caffeine.cache.Cache;
import huanzhao.erp.domain.po.CacheOp;
import huanzhao.erp.domain.constant.CommonConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;


@Component
@Slf4j
public class MessageConsumer {
    @Autowired
    private Cache<String,Object> caffeinCache;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue() /*系统随机生成queue名称*/,
            exchange = @Exchange(value = CommonConstant.FANOUT_EXCHANGE, type = ExchangeTypes.FANOUT)))
    public void receivedFanoutMessage(String msg) {
        log.info("Received fanout message: " + msg);
        // 将消息解析为Cache
        CacheOp cacheOp = JSONUtil.toBean(msg, CacheOp.class);
        switch (cacheOp.getType()) {
            case PUT:
                caffeinCache.put(cacheOp.getKey(), cacheOp.getValue());
                break;
            case DELETE:
                caffeinCache.invalidate(cacheOp.getKey());
                break;
            default:
                break;
        }
    }
}
